//
//  NetDownTalk.m
//  KidReading
//
//  Created by ys on 15/11/5.
//  Copyright © 2015年 刘赞黄Telen. All rights reserved.
//

#import "NetDownTalk.h"
#import "ConstDefine.h"
#import "DBLocalWork.h"

#define __Debug_Log __Debug_Net

@implementation TalkDownInfo
-(void)dealloc{
    self.urlStr = nil;
}

@end


@implementation NetDownTalk

static NetDownTalk *singleNetDownTalk = nil;
+ (NetDownTalk*)shareSingle{
    if (!singleNetDownTalk) {
        singleNetDownTalk = [[NetDownTalk alloc] init];
    }
    return singleNetDownTalk;
}

- (instancetype)init
{
    if (self = [super init]) {
        downloadTalkArray = [[NSMutableArray alloc] initWithCapacity:0];
        delegateArray = [[NSMutableArray alloc] initWithCapacity:0];
        _talkUrlArray = [[NSMutableArray alloc] initWithCapacity:0];
        totelPercentage = 0;
        tempTotelPercentage = 0;
    }
    return self;
}

//封装AFN的download方法
- (NSURLSessionDownloadTask *)downloadTalkFileTaskWithRequest:(NSURLRequest *)request
                                             progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
                                          destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
                                    completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    JRAFURLSessionManager *sessionManager = [[JRAFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    [sessionManager setDownloadTaskDidWriteDataBlock:^(NSURLSession * _Nonnull session, NSURLSessionDownloadTask * _Nonnull downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
        double downloadProgress = totalBytesWritten / (double)totalBytesExpectedToWrite;
        [self _downProgress:downloadProgress];
    }];
    
    return [sessionManager downloadTaskWithRequest:request progress:downloadProgressBlock destination:destination completionHandler:completionHandler];
}

//注册代理
- (void)registerDownTalkStatusNotice:(id<NetDownloadTalksDelegate>)delegate
{
    NSValue* value = [NSValue valueWithNonretainedObject:delegate];
    [delegateArray addObject:value];
}

- (void)unRegisterDownTalkStatusNotice:(id<NetDownloadTalksDelegate>)delegate
{
    NSArray* arr = [NSArray arrayWithArray:delegateArray];
    for (NSValue* value in arr) {
        if([value nonretainedObjectValue] == delegate){
            [delegateArray removeObject:value];
        }
    }
}
//判断是否已经下载Zip包
- (BOOL)isDownedForTalk:(NSInteger)talkid originalID:(NSInteger)originalid edition:(long long)edition
{
    long long bookEdition = [[CacheData shareSingle] getEditionFordownloadingTalk:talkid];
    if(bookEdition == edition){
        NSString* TalkPath = [DataProcessing talkPathForOriginalID:originalid];
        if ([[NSFileManager defaultManager] fileExistsAtPath:TalkPath]) {
#if __Debug_Log
            NSLog(@">>>>>talk文件已下载并解压,跳过下载解压步骤>>>");
#endif
            
            return YES;
        }
    }else{
        NSString* talkPath = [DataProcessing talkPathForOriginalID:originalid];
        if ([[NSFileManager defaultManager] fileExistsAtPath:talkPath]) {
            [[NSFileManager defaultManager] removeItemAtPath:talkPath error:nil];
        }
    }
    return NO;
}

//诊断Talk视频文件是否已经下载
-(BOOL)isDownedTalkVedioForTalkVideoUrl:(NSString *)videoUrl Talk:(NSInteger)talkid VideoID:(NSInteger)videoid originalID:(NSInteger)originalid edition:(long long)edition{
    long long TalkVideoEdition = [[CacheData shareSingle] getEditionFordownloadingTalkVideo:videoid];
    NSString* talkVideoPath = [DataProcessing talkVideoPath];
    NSString* videoFileName = [videoUrl lastPathComponent];
    NSString* full_talkVideoPath = [talkVideoPath stringByAppendingPathComponent:videoFileName];
    if (TalkVideoEdition == edition) {
#if __Debug_Log
        NSLog(@"talkVideoPath: %@",full_talkVideoPath);
        NSLog(@"Talk Video Url = %@",videoUrl);
#endif
        if ([[NSFileManager defaultManager] fileExistsAtPath:full_talkVideoPath]) {
#if __Debug_Log
            NSLog(@">>>>>talk视频已经下载,跳过此视频下载步骤>>>");
#endif
            totelPercentage = totelPercentage + (double)0.95 / 8;
            tempTotelPercentage = totelPercentage;
            for (NSValue* value in delegateArray) {
                id<NetDownloadTalksDelegate> delegate = [value nonretainedObjectValue];
                if ([delegate respondsToSelector:@selector(netDownloadTalkFilePercentage:originalID:)]) {
                    double totelPer = totelPercentage;
                    [DataProcessing do_Main_quick:^{
                        [delegate netDownloadTalkFilePercentage:totelPer originalID:originalid];
                    }];
                    
                }
            }
            return YES;
    }
    }else{
        [DataProcessing deleteTalkVideoFiles:videoFileName];
        
    }
    return NO;

}

//诊断TalkMP3 和 背景 文件是否已经下载
-(BOOL)isDownedTalkVedioForTalkOtherUrl:(NSString *)videoUrl originalID:(NSInteger)originalid{
    
    NSString* talkVideoPath = [DataProcessing talkVideoPath];
    NSString* videoFileName = [videoUrl lastPathComponent];
    NSString* full_talkVideoPath = [talkVideoPath stringByAppendingPathComponent:videoFileName];
#if __Debug_Log
    NSLog(@"talkVideoPath: %@",full_talkVideoPath);
    NSLog(@"Talk Video Url = %@",videoUrl);
#endif
    if ([[NSFileManager defaultManager] fileExistsAtPath:full_talkVideoPath]) {
#if __Debug_Log
        NSLog(@">>>>>talk mp3 背景图片已经下载,跳过此视频下载步骤>>>");
#endif
        totelPercentage = totelPercentage + (double)0.95 / 8;
        tempTotelPercentage = totelPercentage;
        for (NSValue* value in delegateArray) {
            id<NetDownloadTalksDelegate> delegate = [value nonretainedObjectValue];
            if ([delegate respondsToSelector:@selector(netDownloadTalkFilePercentage:originalID:)]) {
                double totelPer = totelPercentage;
                [DataProcessing do_Main_quick:^{
                    [delegate netDownloadTalkFilePercentage:totelPer originalID:originalid];
                }];
                
            }
        }
        return YES;
    }
    return NO;
    
}




//点击Talk现在响应的方法
- (void)downTalkUrl:(NSString*)urlStr withTalkID:(NSInteger)talkid edition:(long long)edition originalID:(NSInteger)originalid{
    
    TalkDownInfo *talkDownInfo_jundge = [downloadTalkArray firstObject];
    if (talkDownInfo_jundge.originalid == originalid) {
        return;
    }else{
        for (TalkDownInfo * talkDownInfo in downloadTalkArray) {
            if (talkDownInfo.originalid == originalid) {
                [downloadTalkArray removeObject:talkDownInfo];
            }
        }
    }
    
    
//    for (TalkDownInfo* talkDownInfo in downloadTalkArray) {
//        if (talkDownInfo.originalid == originalid) {
//            //用户点击的任务在下载队列中
//#if __Debug_Log
//            NSLog(@"正在下载队列 originalID : %d",originalid);
//#endif
//            return;
//        }
//    }
    
    
    if (self.downloadTask) {
        [self.downloadTask cancel];
        [_talkUrlArray removeAllObjects];
    }
    TalkDownInfo *talkDownInfo = [[TalkDownInfo alloc] init];
    talkDownInfo.urlStr = urlStr;
    talkDownInfo.talkid = talkid;
    talkDownInfo.originalid = originalid;
    talkDownInfo.edition = edition;
    [downloadTalkArray insertObject:talkDownInfo atIndex:0];
    //利用AFN进行下载
    [self AFNdownloadTalkUrl:urlStr withTalkID:talkid edition:edition originalID:originalid];
}
//AFN 下载Zip
- (void)AFNdownloadTalkUrl:(NSString*)urlStr withTalkID:(NSInteger)talkid edition:(long long)edition originalID:(NSInteger)originalid{
    totelPercentage = 0;
    tempTotelPercentage = 0;
    if ([self isDownedForTalk:talkid originalID:originalid edition:edition]) {
        totelPercentage = (double)0.05;
        tempTotelPercentage = totelPercentage;
        for (NSValue* value in delegateArray) {
            id<NetDownloadTalksDelegate> delegate = [value nonretainedObjectValue];
            if ([delegate respondsToSelector:@selector(netDownloadTalkZipFinished:)]) {
                [DataProcessing do_Main_quick:^{
                    [delegate netDownloadTalkZipFinished:originalid];
                }];
            }
        }
        NSDictionary *unZipDictionary = [DataProcessing getTalkJsonInfo:originalid];
        //NSLog(@"%@",unZipDictionary);
        
        //此处需要加判断:判断本地是否已经存在对应Talk的视频文件
        
        [self downloadTalkVideoWithJsonDic:unZipDictionary OriginalID:originalid TalkID:talkid edition:edition];
    }else{
        //通过url请求数据 下载talkZip包
        //NSString *full_talk_url = [NSString stringWithFormat:@"http://10.135.195.180:8086/tushu/talk/zip/%d/20151107/%d.zip",originalid,originalid];
        NSString *full_talk_url = [DataProcessing fullTalkZipFileUrl:urlStr];
        //文件网络请求URL
        NSURLRequest *talkZipRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:full_talk_url]];
        //下载Zip的文件路径
        NSString *talkZipPath = [DataProcessing storeTalkZipPathForOriginalID:originalid];
        //下载
        self.downloadTask = [self downloadTalkFileTaskWithRequest:talkZipRequest progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            //将文件路径转化为文件URL 提供存储的路径
            NSURL* talkZipPathUrl = [NSURL fileURLWithPath:talkZipPath];
            //该方法为自动拼接服务器所给文件的文件名添加到文件路径中
            return talkZipPathUrl;
            
        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            if (!error) {
                [[CacheData shareSingle] updateTalk:talkid DownEdition:edition];
                tempTotelPercentage = totelPercentage;
                for (NSValue* value in delegateArray) {
                    id<NetDownloadTalksDelegate> delegate = [value nonretainedObjectValue];
                    if ([delegate respondsToSelector:@selector(netDownloadTalkZipFinished:)]) {
                        [DataProcessing do_Main_quick:^{
                            [delegate netDownloadTalkZipFinished:originalid];
                        }];
                    }
                    
                }
                BOOL unZipResult = [DataProcessing unZipTalkZipPath:talkZipPath forOriginalID:originalid];
                if (unZipResult) {
                    [DataProcessing deleteTalkZips:originalid];
                }
                
                NSDictionary *unZipDictionary = [DataProcessing getTalkJsonInfo:originalid];
                //NSLog(@"%@",unZipDictionary);
                //调取方法下载视频文件
                [self downloadTalkVideoWithJsonDic:unZipDictionary OriginalID:originalid TalkID:talkid edition:edition];
            }else{
                if ([error.localizedDescription isEqualToString:@"cancelled"]) {
                    for (NSValue* value in delegateArray) {
                        id<NetDownloadTalksDelegate> delegate = [value nonretainedObjectValue];
                        if ([delegate respondsToSelector:@selector(netDownloadTalkFileFailed:)]) {
                            [DataProcessing do_Main_quick:^{
                                [delegate netDownloadTalkFileFailed:originalid];
                            }];
                        }
                    }
                    [self cancelDownloadTalkTaskWithOriginalID:originalid];
                }
            }
            
        }];
        //开始下载
        [self.downloadTask resume];
    }
}

- (void)_downProgress:(double)downloadProgress
{
    TalkDownInfo *talkDownInfo = [downloadTalkArray firstObject];
    NSString* TalkPath = [DataProcessing talkPathForOriginalID:talkDownInfo.originalid];
    if ([[NSFileManager defaultManager] fileExistsAtPath:TalkPath]) {
        totelPercentage = tempTotelPercentage + downloadProgress * 95 / 100 / 8;
    }else{
        totelPercentage = tempTotelPercentage + downloadProgress / 20;
    }
    
#if __Debug_Log
    NSLog(@"Download at %f", totelPercentage);
#endif
    
    for (NSValue* value in delegateArray) {
        id<NetDownloadTalksDelegate> delegate = [value nonretainedObjectValue];
        if ([delegate respondsToSelector:@selector(netDownloadTalkFilePercentage:originalID:)]) {
            [DataProcessing do_Main_quick:^{
                [delegate netDownloadTalkFilePercentage:totelPercentage originalID:[(TalkDownInfo *)[downloadTalkArray firstObject] originalid]];
            }];
            
        }
    }

}


-(void)downloadTalkVideoWithJsonDic:(NSDictionary *)dictionary OriginalID:(NSInteger)originalid TalkID:(NSInteger)talkid edition:(long long)edition{
    NSArray *videoIDArr = [dictionary objectForKey:@"download"];
    NSString *backgroundUrl = [dictionary objectForKey:@"background"];
    NSString *mp3Url = [dictionary objectForKey:@"mp3"];
    NSString *videoIDStr = [NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@",videoIDArr[0],videoIDArr[1],videoIDArr[2],videoIDArr[3],videoIDArr[4],videoIDArr[5]];
    DBHelper *dbHelper = [DBHelper shareInstance];
    //从数据库查询TalkVedio的视频下载Url
    [dbHelper selectTalkVedioes:videoIDStr complete:^(NSDictionary *reDict) {
        NSArray *talkVideoInfoArr = [reDict objectForKey:@"talkVedio"];
        for (NSDictionary *talkInfoDic in talkVideoInfoArr) {
            NSString *videoUrl = [talkInfoDic objectForKey:@"videoUrl"];
            NSInteger videoEdition = [[talkInfoDic objectForKey:@"edition"] integerValue];
            NSInteger videoid = [[talkInfoDic objectForKey:@"videoId"] integerValue];
            [[CacheData shareSingle] updateTalkVideo:videoid DownEdition:videoEdition];
            if (![self isDownedTalkVedioForTalkVideoUrl:videoUrl Talk:talkid VideoID:videoid originalID:originalid edition:videoEdition]) {
                [self.talkUrlArray addObject:videoUrl];
            }
        }
        
        if (![self isDownedTalkVedioForTalkOtherUrl:backgroundUrl originalID:originalid]) {
            [self.talkUrlArray addObject:backgroundUrl];
        }
        
        
        if (![self isDownedTalkVedioForTalkOtherUrl:mp3Url originalID:originalid]) {
            [self.talkUrlArray addObject:mp3Url];
        }
        
        if (_talkUrlArray.count != 0) {
            [self downloadTalkVideoWithUrl:self.talkUrlArray[0] withTalkID:talkid edition:edition originalID:originalid];
        }else{
            [self allTalkFileDownFinishWithOriginalID:originalid];
        }
        
    }];

}

//下载talkVideo
- (void)downloadTalkVideoWithUrl:(NSString*)talkUrlStr withTalkID:(NSInteger)talkid edition:(long long)edition originalID:(NSInteger)originalid{
    //NSString *full_talkVideo_url = [NSString stringWithFormat:@"%@%@",__URL_Base_ , talkUrlStr];
    NSString *full_talkVideo_url = [DataProcessing fullTalkZipFileUrl:talkUrlStr];
    //文件网络请求URL
    NSURLRequest *talkZipRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:full_talkVideo_url]];
    //下载Vedio的文件路径
    NSString *talkVideoPath = [DataProcessing talkVideoPath];
    //下载
    self.downloadTask = [self downloadTalkFileTaskWithRequest:talkZipRequest progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //将文件路径转化为文件URL 提供存储的路径
        NSURL* talkVideoUrl = [NSURL fileURLWithPath:talkVideoPath];
        //该方法为自动拼接服务器所给文件的文件名添加到文件路径中
        NSURL* currentTalkVideoUrl = [talkVideoUrl URLByAppendingPathComponent:[response suggestedFilename]];
#if __Debug_Log
        NSLog(@">>>>> %@",targetPath);
        NSLog(@">>>>> %@",currentTalkVideoUrl);
#endif
        return currentTalkVideoUrl;
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (!error) {

            if(self.talkUrlArray.count > 0)[self.talkUrlArray removeObjectAtIndex:0];
            
            for (NSValue* value in delegateArray) {
                id<NetDownloadTalksDelegate> delegate = [value nonretainedObjectValue];
                if ([delegate respondsToSelector:@selector(netDownloadTalkFilePercentage:originalID:)]) {
                    [DataProcessing do_Main_quick:^{
                        [delegate netDownloadTalkFilePercentage:totelPercentage originalID:originalid];
                    }];
                }
            }
            tempTotelPercentage = totelPercentage;
            //确定视频文件是否已经下载完
            if (self.talkUrlArray.count != 0) {
                //
                //if (![self isDownedTalkVedioForTalkVideoUrl:self.talkUrlArray[0] Talk:talkid originalID:originalid edition:edition]){
                    [self downloadTalkVideoWithUrl:self.talkUrlArray[0] withTalkID:talkid edition:edition originalID:originalid];
                //}
            }else{
                [self allTalkFileDownFinishWithOriginalID:originalid];
            }
        }else{
            if (![error.localizedDescription isEqualToString:@"cancelled"]) {
                for (NSValue* value in delegateArray) {
                    id<NetDownloadTalksDelegate> delegate = [value nonretainedObjectValue];
                    if ([delegate respondsToSelector:@selector(netDownloadTalkFileFailed:)]) {
                        [DataProcessing do_Main_quick:^{
                            [delegate netDownloadTalkFileFailed:originalid];
                        }];
                    }
                }
                [self cancelDownloadTalkTaskWithOriginalID:originalid];
            }
        }
        
    }];
    //开始下载
    [self.downloadTask resume];
}

-(void)allTalkFileDownFinishWithOriginalID:(NSInteger)originalid{
    
    if (downloadTalkArray.count != 0) {
        [downloadTalkArray removeObjectAtIndex:0];
    }
    
    if (downloadTalkArray.count != 0) {
        TalkDownInfo *talkDownInfo = [downloadTalkArray firstObject];
        [self AFNdownloadTalkUrl:talkDownInfo.urlStr withTalkID:talkDownInfo.talkid edition:talkDownInfo.edition originalID:talkDownInfo.originalid];
    }
    for (NSValue* value in delegateArray) {
        id<NetDownloadTalksDelegate> delegate = [value nonretainedObjectValue];
        if ([delegate respondsToSelector:@selector(netDownloadTalkFilePercentage:originalID:)]) {
            [DataProcessing do_Main_quick:^{
                [delegate netDownloadTalkFilePercentage:1 originalID:originalid];
            }];
        }
        if ([delegate respondsToSelector:@selector(netDownloadTalkAllFinished:)]) {
            [DataProcessing do_Main:^{
                [delegate netDownloadTalkAllFinished:originalid];
            } delay:0.1];
        }
    }
    totelPercentage = 0;
    tempTotelPercentage = 0;
}


//删除下载任务并移除队列中的任务
-(void)cancelAllDownloadTalkTask{
    [self.downloadTask cancel];
    [downloadTalkArray removeAllObjects];
}

//根据originalid删除队列中指定的任务
-(void)cancelDownloadTalkTaskWithOriginalID:(NSInteger)originalid{
    TalkDownInfo *talkDownInfo  = [downloadTalkArray firstObject];
    if (talkDownInfo && originalid == talkDownInfo.originalid) {
        [self.downloadTask cancel];
        if (downloadTalkArray.count != 0) {
            [downloadTalkArray removeObjectAtIndex:0];
        }
        TalkDownInfo *nextTalkDownInfo = [downloadTalkArray firstObject];
        [self AFNdownloadTalkUrl:nextTalkDownInfo.urlStr withTalkID:nextTalkDownInfo.talkid edition:nextTalkDownInfo.edition originalID:nextTalkDownInfo.originalid];
    }else{
        for (TalkDownInfo *talkInfo in downloadTalkArray) {
            if (talkInfo.originalid == originalid) {
                [downloadTalkArray removeObject:talkInfo];
            }
        }
    }
}

//判断talk是否有未下载的文件
- (void)checkDownTalkUrl:(NSString*)urlStr withTalkID:(NSInteger)talkid edition:(long long)edition originalID:(NSInteger)originalid complete:(void(^)(BOOL isDone)) complete{
    if (!complete) {
        return;
    }
    if (![self isDownedForTalk:talkid originalID:originalid edition:edition]){
        complete(NO);
        return;
    }
    NSDictionary *unZipDictionary = [DataProcessing getTalkJsonInfo:originalid];
    NSArray *videoIDArr = [unZipDictionary objectForKey:@"download"];
    NSString *backgroundUrl = [unZipDictionary objectForKey:@"background"];
    NSString *mp3Url = [unZipDictionary objectForKey:@"mp3"];
    NSString *videoIDStr = [NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@",videoIDArr[0],videoIDArr[1],videoIDArr[2],videoIDArr[3],videoIDArr[4],videoIDArr[5]];
    DBHelper *dbHelper = [DBHelper shareInstance];
    //从数据库查询TalkVedio的视频下载Url
    [dbHelper selectTalkVedioes:videoIDStr complete:^(NSDictionary *reDict) {
        NSArray *talkVideoInfoArr = [reDict objectForKey:@"talkVedio"];
        for (NSDictionary *talkInfoDic in talkVideoInfoArr) {
            NSString *videoUrl = [talkInfoDic objectForKey:@"videoUrl"];
            NSInteger videoEdition = [[talkInfoDic objectForKey:@"edition"] integerValue];
            NSInteger videoid = [[talkInfoDic objectForKey:@"videoId"] integerValue];
            [[CacheData shareSingle] updateTalkVideo:videoid DownEdition:videoEdition];
            if (![self isDownedTalkVedioForTalkVideoUrl:videoUrl Talk:talkid VideoID:videoid originalID:originalid edition:videoEdition]) {
                complete(NO);
                return;
            }
        }
        
        if (![self isDownedTalkVedioForTalkOtherUrl:backgroundUrl originalID:originalid]) {
            complete(NO);
            return;
        }
        
        
        if (![self isDownedTalkVedioForTalkOtherUrl:mp3Url originalID:originalid]) {
            complete(NO);
            return;
        }
        
        complete(YES);
    }];
    
    //complete(YES);
}





@end
